/* eslint-disable default-case */
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  getDeduAssDetail,
  getRedEmpDetail,
  getRemoveRsnList,
  getAssUpdateDetail,
  addSubmit,
  updateSubmit,
  getDownloadInfo,
  getUploadProgress,
  uploadFileRedAss,
} from '@/services/redass';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

// 非常重要属性
const namespace = 'redass';
const ModelAddEmp = {
  namespace,
  state: {
    sendId: null,
    assList: [], // 	雇员所有险种
    responseDeduAssBaseDto: {}, // 基本信息
    responseDeduAssSendDto: {}, // 派单信息
    responseHaveAssDtos: [], // 已有险种列表
    RemoveRsnList: [], // 离职原因
    tableId: 1,
    assInfoDtos: [{ id: 0, ass: undefined, endDate: undefined, assList: [] }], // 	减少险种集合
    // 详情
    responseDeduAssDto: {}, // 已经减少的险种
    responseDeduInfo: {}, // 减员信息、
    rsponseDeduPdDto: {}, // 产品信息
    handDto: [], // 	办理备注
    contRecDtoList: [], // 联系记录
    batchQuery: {
      progressPercent: 0,
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/deduTask/export/error', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    tempType: null,
  },
  effects: {
    // 查询已有社保险种列表:查询信息
    *fetchAssDetail({ payload }, { call, put, select }) {
      let assInfoDtos = yield select(state => state.redass.assInfoDtos);
      const response = yield call(
        payload.deduTaskId ? getAssUpdateDetail : getDeduAssDetail,
        payload
      );
      if (response.success) {
        const responsegetRemoveRsnList = yield call(getRemoveRsnList);
        if (response.data.assList.length) {
          assInfoDtos = assInfoDtos.map(item => ({ ...item, assList: response.data.assList }));
        }
        if (payload.deduTaskId) {
          // 修改处理表格数据
          assInfoDtos = [];
          if (
            response.data.responseDeduAssDto &&
            response.data.responseDeduAssDto.assDetailDtoList &&
            response.data.responseDeduAssDto.assDetailDtoList.length
          ) {
            assInfoDtos = response.data.responseDeduAssDto.assDetailDtoList.map((item, index) => ({
              ...item,
              id: `${new Date().getTime()}-${index}`,
              lastDay: moment(item.endDate).daysInMonth(),
              ass: item.ass.split(','),
              assList: response.data.assList,
            }));
          }
        }
        yield put({
          type: 'updateModelData',
          payload: {
            ...payload,
            ...response.data,
            assInfoDtos,
            RemoveRsnList: responsegetRemoveRsnList.data || [],
          },
        });
      } else {
        message.warning(response.message || '获取人员信息：服务端错误');
      }
    },
    // 详情数据
    *fetchRedAssDetail({ payload }, { call, put, select }) {
      let assInfoDtos = yield select(state => state.redass.assInfoDtos);
      const response = yield call(getRedEmpDetail, payload);
      if (response.success) {
        if (
          response.data.rsponseDeduPdDto &&
          response.data.rsponseDeduPdDto.pdDetailDtos &&
          response.data.rsponseDeduPdDto.pdDetailDtos.length
        ) {
          assInfoDtos = assInfoDtos.map(item => ({
            ...item,
            assList: response.data.rsponseDeduPdDto.pdDetailDtos,
          }));
        }
        yield put({
          type: 'updateModelData',
          payload: {
            ...payload,
            ...response.data,
            assInfoDtos,
          },
        });
      } else {
        message.warning(response.message || '获取人员信息：服务端错误');
      }
    },

    // 提交数据
    *submit({ payload }, { call, put, select }) {
      const assInfo = yield select(state => state.redass);
      const { sendId } = assInfo;
      let submitData = { sendId, ...payload.values };
      submitData = payload.deduTaskId
        ? { ...submitData, deduTaskId: payload.deduTaskId }
        : submitData;
      const response = yield call(payload.deduTaskId ? updateSubmit : addSubmit, submitData);
      if (response.success) {
        message.success(payload.deduTaskId ? '保存成功!' : '减少险种成功！');
        yield put(routerRedux.push('/customservicemanage/reduceemployee/index'));
      } else {
        message.warning(`${response.message || '保存失败！'}`);
      }
    },
    // 获取下载模板fileId fileName
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },

    // 上传文件:批量进度
      uploadFileWithProgress:[
        function* ({ payload }, { call, put }) {
        try {
          const response = yield call(uploadFileRedAss, payload);
          if (response.success) {
            yield put({
              type: 'setTempType',
              payload: { tempType: response.data && response.data.tempType },
            });
            // 不是100表示需要走队列
            if (response.data && response.data.successProp !== 100) {
              const { batchId } = response.data;
              const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

              yield put.resolve({
                type: `socket/${SocketActions.subSocketChannel}`,
                payload: {
                  batchTask,
                },
              });
              // 订阅成功后再触发进度条
              yield put({
                type: 'updateModelData',
                payload: { showProgress: true },
              });
            } else {
              yield put({
                type: 'handleBatchTask',
                payload: response.data,
              });
            }
          } else {
            message.warning(response.message || '上传文件错误：服务器端错误');
          }

          // 无需返回response对象
        } catch (e) {
          console.error(e);
        }
      },
      { type: 'throttle', ms: 10000 }
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.redass);
      const { tempType } = state;
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          tempType,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setTempType(state, { payload }) {
      return {
        ...state,
        tempType: payload.tempType,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
